package com.delivery.www.dao.DaoImpl;

import com.delivery.www.dao.CouponDao;
import com.delivery.www.po.Coupon;
import com.delivery.www.util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CouponDaoImpl implements CouponDao {
    //获取已有抵用券
    @Override
    public List<Coupon> getCoupon(int storeId) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<Coupon> coupons = new ArrayList<>();
        Object[] params = {storeId};
        String sql = "select * from coupon c where store_id = ?";
        rs = JdbcUtils.excute(connection, pstm, rs, sql, params);
        try {
            while (rs.next()) {
                Coupon coupon = new Coupon();
                coupon.setCouponId(rs.getInt("coupon_id"));
                coupon.setStoreId(rs.getInt("store_id"));
                coupon.setValue(rs.getInt("value"));
                coupon.setMin(rs.getInt("min"));
                coupons.add(coupon);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JdbcUtils.closeResource(connection, pstm, rs);
        return coupons;
    }

    //商家新增抵用券
    @Override
    public int addCoupon(int storeId, int value, int min) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        Object[] params = {storeId, value, min};
        String sql = "insert into coupon (store_id,value,min) values (?,?,?)";
        int excute = JdbcUtils.excute(connection, pstm, sql, params);
        JdbcUtils.closeResource(connection, pstm, null);
        return excute;
    }

    //删除抵用券
    @Override
    public int deleteCoupon(int couponId) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        Object[] params = {couponId};
        String sql = "delete from coupon where coupon_id = ?";
        int excute = JdbcUtils.excute(connection, pstm, sql, params);
        JdbcUtils.closeResource(connection, pstm, null);
        return excute;
    }

    @Override
    public Coupon getOneCoupon(int couponId) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Coupon coupon = null;
        Object[] params = {couponId};
        String sql = "select c.value,c.min from coupon c where coupon_id = ?";
        rs = JdbcUtils.excute(connection, pstm, rs, sql, params);
        try {
            if (rs.next()) {
                coupon = new Coupon();
                coupon.setValue(rs.getInt("value"));
                coupon.setMin(rs.getInt("min"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JdbcUtils.closeResource(connection, pstm, rs);
        return coupon;
    }
}
